package stack;


import java.util.Scanner;
//用数组模拟栈
public class ArrayStackDemo {
    public static void main(String[] args) {
        int i = 900000 * 1147;
        ArrayStack arrayStack = new ArrayStack(5);
        char key = ' ';//接收用户输入
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;
        while (loop) {
            System.out.println("s(show):显示栈");
            System.out.println("e(exit):退出栈");
            System.out.println("a(add):添加数据到栈");
            System.out.println("g(get):从栈获取数据");
            key = scanner.next().charAt(0);//接受的字符
            switch (key) {
                case 's':
                    arrayStack.list();
                    break;
                case 'a':
                    System.out.println("请输入1个数");
                    int n = scanner.nextInt();
                    arrayStack.push(n);
                    break;
                case 'g':
                    try {
                        int num = arrayStack.pop();
                        if (num > 0){
                            System.out.printf("取出的数据是%d\n", num);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case 'e':
                    scanner.close();
                    loop = false;
                    break;
                default:
                    break;
            }
        }
        System.out.println("程序退出");
    }

    static class ArrayStack {
        private int maxsize;
        private int top = -1;//栈顶
        private int[] arr;

        public ArrayStack(int maxsize) {
            this.maxsize = maxsize;
            arr = new int[maxsize];
        }

        //是否栈满
        public boolean isFull() {
            return top == maxsize - 1;
        }

        //是否栈空
        public boolean isEmpty() {
            return top == -1;
        }

        //入栈
        public void push(int num) {
            if (isFull()) {
                System.out.println("栈满了，不能入栈。");
                return;
            }
            top++;
            arr[top] = num;
        }

        //出栈
        public int pop() {
            if (isEmpty()) {
                System.out.println("栈空了，不能出栈。");
                return -1;
            }
            int i = arr[top];
            top--;
            return i;
        }

        public void list() {
            if (isEmpty()) {
                System.out.println("栈空了，无法遍历。");
                return;
            }
            for (int i = top; i >= 0; i--) {
                System.out.printf("stack[%d] == %d \n", i, arr[i]);
            }
        }
    }
}
